import { session } from '@/utils/storage'
import { useRouteStore } from '@/store/routes'
import { whiteList } from './basics.router'
import type { Router } from 'vue-router'
const loginPath = '/login'
const defultPath = '/'
export const permission = (router: Router) => {
  let registerRouteFresh = true
  // let registerRouteFresh = !session.get('routes')?.routes
  router.beforeEach((to, from, next) => {
    if (session.get('token')) {
      if (to.path === loginPath) {
        next({ path: defultPath })
      } else {
        if (registerRouteFresh) {
          const routeStore = useRouteStore()
          routeStore?.fetchMenuList({
            router,
            callback: () => {
              next({ ...to, replace: true })
              registerRouteFresh = false
            }
          })
        } else {
          next()
        }
      }
    } else {
      if (whiteList.includes(to.path)) {
        next()
      } else {
        next({ path: loginPath, query: { redirect: to.fullPath } })
      }
    }
  })
}